import WebSocket from 'ws';
import {Package, Protocol} from "./prot";
import { ProtoMod } from '../app/package/protocol/proto';
import { wxLogin_req } from '../app/package/protocol/ProtoDef';

const ws = new WebSocket('ws://127.0.0.1:3010');
ws.onopen = function () {
    console.log('ws open');
    handshake()
};
ws.onmessage = function (evt) {
    try {
        const res = Package.decode(evt.data)
        if(res.type === 1) {
            ack()
            test();
        }else if(res.type === 4){
            console.log("正常返回")
            console.log(ProtoMod.unPack(res.body));
        }else if(res.type === 5) {
            console.log("被踢了");
            console.log(ProtoMod.unPack(res.body));
        }
    }catch (e) {
        console.log("发生异常", e)
    }
};
ws.onclose = function () {
    console.log('ws close');
};
ws.onerror = function () {
    console.log('ws error');
};

function handshake() {
    let JS_WS_CLIENT_TYPE = 'js-websocket';
    let JS_WS_CLIENT_VERSION = '0.0.1';
    let handshakeBuffer = {
        'sys': {
            type: JS_WS_CLIENT_TYPE,
            version: JS_WS_CLIENT_VERSION,
            rsa: {},
            protoVersion: ''
        },
        'user': {
        }
    };
    handshakeBuffer.sys.protoVersion = "1";
    // handshakeBuffer.user = undefined;
    var obj = Package.encode(Package.TYPE_HANDSHAKE, Protocol.strencode(JSON.stringify(handshakeBuffer)));
    ws.send(obj);
}

function ack() {
    var obj = Package.encode(Package.TYPE_HANDSHAKE_ACK);
    ws.send(obj)
}

function wsSend(requestData) {
    const bin = ProtoMod.pack(requestData);
    let aa = Package.encode(Package.TYPE_DATA, bin);
    ws.send(aa);
}

function test() {
    const req = new wxLogin_req();
    req.openid = "wx";
    wsSend(req);
}
